<?php

/**
 * 转写文本处理类
 */

namespace app\common;

use app\common\Script;

class Content
{
    //数组化文本
    protected $_arr;
    //文本格式化文本
    protected $_txt;
    //上一次结束时间
    protected $_last_time;
    //构造函数
    public function __construct($in = null)
    {
        if (is_array($in)) {
            $this->setJson($in);
        }
    }

    //设置初始文档
    public function setJson($arr)
    {
        $this->_arr = $arr;
        return $this;
    }

    //返回json格式转写结果
    public function getJson()
    {
        if (isset($this->_arr) && is_array($this->_arr)) {
            return json_encode($this->_arr, JSON_UNESCAPED_UNICODE);
        }
        throw new \Exception('array error');
    }

    //返回数组格式转写结果
    public function getArr()
    {
        return $this->_arr;
    }

    //返回文字格式转写结果
    public function getTxt()
    {
        return $this->_txt;
    }

    //重置
    public function initialize()
    {
        $this->_txt = null;
        $this->_arr = null;
        $this->_last_time = null;
    }

    //非实时结果合并
    public function notReal()
    { }

    //实时
    public function real()
    { }

    /**
     * 转换成文字格式
     */
    public function deword()
    {
        if (!isset($this->_arr)) {
            throw new \Exception('array error');
        }
        $txt = '';
        $sc = 0;
        for ($i = 0; $i < count($this->_arr); $i++) {
            if ($sc != $this->_arr[$i]['sc']) {
                $sc = $this->_arr[$i]['sc'];
                $txt .= '{$rep}' . '&#160;&#160;' . $this->_arr[$i]['txt'];
                continue;
            }
            $txt .= $this->_arr[$i]['txt'];
        }
        return '&#160;&#160;' . $txt;
    }

    /**
     * 转换成文字格式
     */
    public function deword_role()
    {
        if (!isset($this->_arr)) {
            throw new \Exception('array error');
        }
        $txt = '';
        $sc = 0;
        for ($i = 0; $i < count($this->_arr); $i++) {
            $txt .= $this->_arr[$i]['speaker'] . ":" . $this->_arr[$i]['txt'] . '{$rep}';
        }
        return $txt;
    }

    /**
     * Json分段
     */
    public function paragraphToTen()
    {
        if (isset($this->_arr)) {
            $sc = 0;
            $len = 0;
            foreach ($this->_arr as &$str) {
                $len += strlen(utf8_decode($str['txt']));
                $str['sc'] = $sc;
                // if($len >= 100 && preg_match("/(\.|\!|\?|\。|\？|\！)$/",$str['txt'])){
                //     $sc++;
                //     $len = 0;
                // }
                if($len >= 100 && preg_match("/(\。)$/",$str['txt'])){
                    $sc++;
                    $len = 0;
                }
            }
        }
        return $this;
    }

    public function paragraph()
    {
        if (isset($this->_arr)) {
            for ($i = 0; $i < count($this->_arr); $i++) {
                $this->_arr[$i]['sc'] = $i;
            }
        }
        return $this;
    }

    /**
     * 去除敏感词
     *
     * @return void
     * @Description
     * @example
     * @author Kelike
     * @since
     */
    public function sensitive()
    {
        if(isset($this->_arr)) {
            $json = json_encode($this->_arr, JSON_UNESCAPED_UNICODE);
            $script = new Script();
            $result = $script->removeSensitiveWords($json);
            $this->_arr = json_decode($result, true);
        }
        return $this;
    }

    /**
     * 去除语气词
     */
    public function modal()
    {
        if (isset($this->_arr)) {
            $json = json_encode($this->_arr, JSON_UNESCAPED_UNICODE);
            $script = new Script();
            $result = $script->removeModalWords($json);
            $json = str_replace(['"txt":",', '"txt":"}', '"sc":"}'], ['"txt":"",', '"txt":""}', '"sc":""}'], trim($result));
            $this->_arr = json_decode($json, true);
        }
        return $this;
    }

    /**
     * 获取摘要
     */
    public function abstract()
    {
        if (isset($this->_arr)) {
            $_txt = '';
            foreach ($this->_arr as $val) {
                $_txt .= $val['txt'];
            }
            $_txt = str_replace("\n", "", $_txt);
            //
            $script = new Script();
            $result = $script->getTransformContentAbstract($_txt);
            // $num = ceil(strlen($_txt) / (3 * 2000));
            // //shell命令获取摘要
            // $commond = 'python /home/wwwroot/default/data/summary.py ' . $num . ' ' . $_txt;
            // exec($commond, $result);
            // unset($result[0]);
            $_txt = '';
            for ($i = 1; $i <= count($result); $i++) {
                $_txt .= $i . '、' . $result[$i] . "\n";
            }
            //$result = str_replace(["、，","、。","、？"], "、", $result);
            return $_txt;
        }
        throw new \Exception('array error');
    }

    /**
     * 按时间顺序 将文字添加如arr中
     * $content = new Content();
     * foreach($speech['list'] as $sentence){
     *    $content->push($sentence['txt'], $sentence['time']);
     * }
     * var_dump($content->getArr());
     */
    public function push($txt, $time, $speaker = '未标记')
    {
        //没有开始将文件制空
        if (!isset($this->_last_time)) {
            $this->_arr = [];
            $this->_last_time = 0;
        }
        $this->_arr[] = [
            'startTime' => $this->_last_time . "",
            'endTime' => ($this->_last_time += $time) . "",
            'txt' => $txt,
            'speaker' => $speaker
        ];
        return $this;
    }

    /**
     * 转换arr, 为srt字幕格式文件
     */
    public function srt()
    {
        if (isset($this->_arr)) {
            $srt = '';
            for ($i = 0; $i < count($this->_arr); $i++) {
                $srt .= $i + 1 . "\r\n" . $this->_srt($this->_arr[$i]) . "\r\n";
            }
            return $srt;
        }
        throw new \Exception('array error');
    }

    /**
     * 
     */
    protected function _srt($array)
    {
        $_str = $this->formatSeconds($array['startTime']) . " --> " . $this->formatSeconds($array['endTime']) . "\r\n" . $array['txt'];
        $_str = isset($array['translate']) ? $_str . "\r\n" . $array['translate'] : $_str;
        return $_str;
    }

    function formatSeconds($seconds)
    {
        $hours = 0;
        $milliseconds = str_replace("0.", '', $seconds - floor($seconds));

        if ($seconds > 3600) {
            $hours = floor($seconds / 3600);
        }
        $seconds = $seconds % 3600;


        return str_pad($hours, 2, '0', STR_PAD_LEFT)
            . gmdate(':i:s', $seconds)
            . ($milliseconds ? "," . substr($milliseconds, 0, 3) : ',000');
    }
}
